package com.fp.m7.dao;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.fp.m7.api.util.Clock;
import com.fp.m7.model.Account;
import com.fp.m7.model.Follow;
import com.fp.m7.repository.FollowRepository;
import com.google.common.collect.Lists;

@Transactional
public class FollowDaoImpl implements FollowDao {

	@Autowired
	private FollowRepository repository;

	@Autowired
	private Neo4jTemplate template;

	@Autowired
	private Clock clock;

	@Override
	public Follow follow(Account follower, Account followed) {
		if (!isFollowing(follower, followed)) {
			Follow follow = new Follow(follower, followed);
			follow.setAuditCD(clock.getDateAsLong());
			return template.save(follow);
		}
		return null;
	}

	@Override
	public Follow unfollow(Account follower, Account followed) {
		Set<Follow> existing = repository.isFollowing(follower, followed);
		if (!existing.isEmpty()) {
			Follow single = existing.iterator().next();
			single.setAuditDD(clock.getDateAsLong());
			return template.save(single);
		}
		return null;
	}

	@Override
	public boolean isFollowing(Account user, Account other) {
		Set<Follow> existing = repository.isFollowing(user, other);
		return !existing.isEmpty();
	}

	@Override
	public boolean isFollowedBy(Account user, Account other) {
		Set<Follow> existing = repository.isFollowing(other, user);
		return !existing.isEmpty();
	}

	@Override
	public List<Account> getFollowersForUser(Account user) {
		return Lists.newArrayList(repository.getFollowersForUser(user));
	}

	@Override
	public List<Account> getFollowedByUser(Account user) {
		return Lists.newArrayList(repository.getFollowedByUser(user));
	}

	@Override
	public int countActiveFollowers(Account followed) {
		Long i = repository.countActiveFollowers(followed);
		return i == null ? 0 : i.intValue();
	}

	@Override
	public int countActivelyFollowed(Account follower) {
		Long i = repository.countActivelyFollowed(follower);
		return i == null ? 0 : i.intValue();
	}

}
